﻿using Newtonsoft.Json;
using PanhuaWin.WMS2NC888;
using PanhuaWin.系统管理;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PanhuaWin.仓库.采购入库
{
    public partial class Form辅材入库审核 : UIPage
    {
        public string docCode;
        public string WorkShop;
        public Form辅材入库审核()
        {
            InitializeComponent();
        }

        private void Form辅材入库审核_Load(object sender, EventArgs e)
        {
            this.uiDatePicker开始日期.Value = DateTime.Today.AddMonths(-1);
            this.uiDatePicker结束日期.Value = DateTime.Today;
            pub.ListWorkShop(pub.sys_user, this.uiComboBoxWorkShop);
        }

        private void uiButton查询_Click(object sender, EventArgs e)
        {
            ListData();
            this.uiDataGridView明细.DataSource = null;
            this.uiDataGridView明细.Refresh();
        }

        private void ListData()
        {
            string sql;
            sql = @"SELECT     guid, StockInType, WorkShopCode, DocCode, DepartCode, CreateID, Creator, CreateDate, ModifyID, Modifier, 
                ModifyDate, ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate
FROM      Bus_StockInM  where 1=1 ";
            sql += " and CreateDate>='" + this.uiDatePicker开始日期.Value + "' and CreateDate< '" + this.uiDatePicker结束日期.Value.AddDays(1) + "'";
            sql += " and WorkShopCode ='" + this.uiComboBoxWorkShop.SelectedValue.ToString() + "'";
            if (!this.uiCheckBox已审核.Checked)
            {
                sql += " and (ApproverID is null or ApproverID ='') ";
            }
            sql += " order by CreateDate ";
            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            this.uiDataGridView主表.AutoGenerateColumns = false;
            this.uiDataGridView主表.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.uiDataGridView主表.DataSource = tb1;
            this.uiDataGridView主表.Refresh();
        }

        private void uiDataGridView主表_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                docCode = this.uiDataGridView主表.Rows[e.RowIndex].Cells["C入库单号"].Value.ToString();
                List行信息(docCode, this.uiDataGridView明细);

                if (this.uiDataGridView主表.Columns[e.ColumnIndex].Name == "C审核")
                {
                    //
                    Approve(docCode);
                }
                else if (this.uiDataGridView主表.Columns[e.ColumnIndex].Name == "C反审核")
                {
                    DeApprove(docCode);

                }
                else if (this.uiDataGridView主表.Columns[e.ColumnIndex].Name == "C删除")
                {
                    Delete(docCode);
                }
                else if (this.uiDataGridView主表.Columns[e.ColumnIndex].Name == "C发送NC")
                {
                    string logsql = @"insert into Sys_Log( BeginDate, BrowserType, RequestParameter,UserName, User_Id ,UserIP,ServiceIP   )";
                    logsql += "values(getdate(),'WinForm','调用NCservice','" + pub.sys_user.UserName + "','" + pub.sys_user.User_Id + "','" + MAC.getIP.getLocalIP() + "','WMS2NC888')";
                    pub.ExecuteSql(pub.ConnectionString, logsql);
                    ///待完成
                    sendToNC(docCode);
                    ListData();
                }
            }
        }
        private void sendToNC(string docCode)
        {
            string sql;
            sql = @"SELECT [guid],[StockInType],[WorkShopCode],[DocCode],[DepartCode],[CreateID],[Creator],CONVERT(varchar(10),[CreateDate],120) CreateDate,[ModifyID],[Modifier]
                  ,[ModifyDate],[ApproverID],[Approver],[ApproverDate],[IsSendToNC],[SendToNCDate]  
                   FROM [Bus_StockInM] where DocCode='" + docCode + "'";
            DataTable dtHeader = pub.GetDataTable(pub.ConnectionString, sql);

            if (dtHeader != null && dtHeader.Rows.Count > 0)
            {
                DataTable dtBody = List行信息(docCode);
                if (dtBody != null && dtBody.Rows.Count > 0)
                {
                    for (int i = 0; i < dtBody.Rows.Count; i++)
                    {
                        NCModel.SetInboundModel setInboundModel = new NCModel.SetInboundModel();
                        setInboundModel.dBillDate = dtHeader.Rows[0]["CreateDate"].ToString();
                        setInboundModel.sendTime = setInboundModel.dBillDate;

                        //仓库 地区 供应商先写死
                        setInboundModel.supplierName = dtBody.Rows[i]["供应商名称"].ToString(); 
                        setInboundModel.supplierCode = dtBody.Rows[i]["供应商编号"].ToString();
                        //查询公司名称 公司编号
                        string sqlworkshop = @"SELECT  [WorkShopName]  FROM [Dic_WorkShop] where WorkShopCode = '" + dtHeader.Rows[0]["WorkShopCode"].ToString() + "'";
                        DataTable dtWorkShop = pub.GetDataTable(pub.ConnectionString, sqlworkshop);
                        if (dtWorkShop != null && dtWorkShop.Rows.Count > 0)
                        {
                            setInboundModel.corpName = dtWorkShop.Rows[0]["WorkShopName"].ToString();
                        }
                        else
                        {
                            MessageBox.Show("未能根据当前入库单公司编号查到对应的公司名称");
                            return;
                        }
                        //仓库 地区 供应商先写死
                        setInboundModel.region = "华中";
                        //查询仓库
                        setInboundModel.warehouse = dtBody.Rows[0]["WarehouseName"].ToString();

                        //List<NCModel.SetInboundItem> itemList = new List<NCModel.SetInboundItem>();

                        ////已经发送的就不发送了
                        //if (dtBody.Rows[i]["IsSendToNC"].ToString() == "Y" && string.IsNullOrEmpty(dtBody.Rows[i]["SendToNCResult"].ToString()))
                        //{
                        //    continue;
                        //}
                        List<NCModel.SetInboundItem> itemList = new List<NCModel.SetInboundItem>();
                        NCModel.SetInboundItem item = new NCModel.SetInboundItem();
                        item.rowNo = dtBody.Rows[i]["Bguid"].ToString();
                        item.itemCode = dtBody.Rows[i]["InventoryCode"].ToString();
                        item.unit = dtBody.Rows[i]["T_GOOD_UNIT"].ToString();
                        //热轧类物料需要产地信息
                        //item.vfree3 = dtBody.Rows[i]["Address"].ToString();
                        item.nnum = dtBody.Rows[i]["QuantityMain"].ToString();
                        item.nastnum = dtBody.Rows[i]["QuantityAssist"].ToString();
                        item.ncLot = dtBody.Rows[i]["Batch"].ToString();
                        
                        //item.nprice = dtBody.Rows[i]["T_GOOD_PRICE"].ToString();
                        //item.vuserdef9 = dtBody.Rows[i]["StorageLocation"].ToString();

                        itemList.Add(item);
                        setInboundModel.items = itemList;
                        string jsonStr = JsonConvert.SerializeObject(setInboundModel);
                        //XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                        ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();
                        string responseStr = client.setInbound(jsonStr);
                        NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                        //调用成功，改写NC状态
                        if (nCResponse.state == 0)
                        {
                            string sqlUpdate = @"update Bus_StockInMaterial set IsSendToNC = 'Y' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',SendToNCResult = '" + nCResponse.result + "' where Bguid = '" + dtBody.Rows[i]["Bguid"].ToString() + "'";
                            int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                            if (r < 1)
                            {
                                MessageBox.Show("更新是否成功发送到NC失败");
                            }
                        }
                        else
                        {
                            string sqlUpdate = @"update Bus_StockInMaterial set IsSendToNC = 'N' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',SendToNCResult = '" + nCResponse.msg + "' where Bguid = '" + dtBody.Rows[i]["Bguid"].ToString() + "'";
                            int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                            if (r < 1)
                            {
                                MessageBox.Show("更新是否成功发送到NC失败");
                            }
                        }
                        // MessageBox.Show(nCResponse.msg);

                    }
                    //setInboundModel.items = itemList;
                    //string jsonStr = JsonConvert.SerializeObject(setInboundModel);
                    ////XmlDocument xml  = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonStr,"root");
                    //WMS2NC.ExternalSystemToNcItfPortTypeClient client = new WMS2NC.ExternalSystemToNcItfPortTypeClient();
                    //string responseStr = client.setInbound(jsonStr);
                    //NCModel.NCResponseModel nCResponse = JsonConvert.DeserializeObject<NCModel.NCResponseModel>(responseStr);
                    ////调用成功，改写NC状态
                    //if (nCResponse.state == 0)
                    //{
                    //    string sqlUpdate = @"update Bus_StockInM set IsSendToNC = 'Y' ,SendToNCDate = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where DocCode = '" + docCode + "'";
                    //    int r = pub.ExecuteSql(pub.ConnectionString, sqlUpdate, "原料卷入库发送到NC");
                    //    if (r < 1)
                    //    {
                    //        MessageBox.Show("更新是否成功发送到NC失败");
                    //    }
                    //}
                    //MessageBox.Show(nCResponse.msg);

                }
                else
                {
                    MessageBox.Show("没查到行未发送NC的信息");
                }
            }
            else
            {
                MessageBox.Show("没查到对应原材料入库单");
            }
        }

        private void List行信息(string doccode, UIDataGridView uiDataGridView)
        {
            string sql;
            sql = @"select Bus_StockInMaterial.guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, Bus_StockInMaterial.T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, InventoryCode, Size, CID, Batch, T_VIEW_CIM.T_GOOD_NAME,T_VIEW_CIM.T_GOOD_MODEL,
                QuantityMain, QuantityAssist,供应商名称,供应商编号,SendToNCResult,IsSendToNC  from Bus_StockInMaterial
                left join T_VIEW_CIM on Bus_StockInMaterial.InventoryCode=T_VIEW_CIM.T_GOOD_CODE   where DocCode='" + doccode + "' order by RowNumber  ";

            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            uiDataGridView.AutoGenerateColumns = false;
            uiDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            uiDataGridView.DataSource = tb1;

            uiDataGridView.Refresh();
        }

        private DataTable List行信息(string doccode)
        {
            string sql;
            sql = @"select Bus_StockInMaterial.guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode,WarehouseName, StorageLocation, T_CONTRACT_CODE, 
                T_ORDER, Bus_StockInMaterial.T_GOOD_UNIT, T_GOOD_NUM, T_GOOD_PRICE, T_GOOD_MONEY, InventoryCode, Size, CID, Batch,
                T_VIEW_CIM.T_GOOD_NAME,T_VIEW_CIM.T_GOOD_MODEL,
                QuantityMain, QuantityAssist  ,SendToNCResult,IsSendToNC,SendToNCDate,供应商名称,供应商编号 from Bus_StockInMaterial
                left join T_VIEW_CIM on Bus_StockInMaterial.InventoryCode=T_VIEW_CIM.T_GOOD_CODE   where DocCode='" + doccode + "' and (IsSendToNC <> 'Y' or IsSendToNC is null) order by RowNumber  ";

            DataTable tb1 = pub.GetDataTable(pub.ConnectionString, sql);
            return tb1;
        }

        private void Delete(string docCode)
        {
            
        }

        private void DeApprove(string doccode)
        {
            //原料的卷未被出库才能反审核
            string sql;
            sql = @"SELECT    ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate  FROM      Bus_StockInM where docCode='" + doccode + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                sql = @"select WorkShopCode,WarehouseCode,StorageLocation, InventoryCode, Batch,QuantityMain  FROM      Bus_StockInMaterial where  docCode='" + doccode + "' ";

                DataTable tb2 = pub.GetDataTable(pub.ConnectionString, sql);

                if (tb2.Rows.Count > 0)
                {
                    ///检查库存够不够反审核
                    for (int k = 0; k < tb2.Rows.Count; k++)
                    {
                        string WorkShopCode = tb2.Rows[k]["WorkShopCode"].ToString();
                        string WarehouseCode = tb2.Rows[k]["WarehouseCode"].ToString();
                        string StorageLocation = tb2.Rows[k]["StorageLocation"].ToString();
                        string InventoryCode = tb2.Rows[k]["InventoryCode"].ToString();
                        string Batch = tb2.Rows[k]["Batch"].ToString();
                        decimal QuantityMain = pub.Todecimal(tb2.Rows[k]["QuantityMain"].ToString());

                        decimal 现存量 = pub.GetMaterialCurrentStock(WorkShopCode, WarehouseCode, StorageLocation, InventoryCode, Batch);
                        if (现存量 >= QuantityMain)
                        {

                        }
                        else
                        {
                            MessageBox.Show("辅料【" + InventoryCode + "," + Batch + "】在【" + WarehouseCode + "," + StorageLocation + "】库存不够，不能反审核!", "提示", MessageBoxButtons.OK);
                            return;
                        }
                    }
                    if (tb.Rows[0]["Approver"].ToString() != "")
                    {
                        sql = "update Bus_StockInM set ApproverID='',Approver='',ApproverDate=NULL where docCode='" + doccode + "' ";
                        if (pub.ExecuteSql(pub.ConnectionString, sql, "辅料入库单反审核") > 0)
                        {
                            MessageBox.Show("反审核成功!", "提示", MessageBoxButtons.OK);
                            ListData();
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("尚未审核了，不能反审核!", "提示", MessageBoxButtons.OK);
                        return;
                    }



                }
                else
                {
                    MessageBox.Show("该单据没有明细行,请检查!", "提示", MessageBoxButtons.OK);
                    return;
                }



                if (tb.Rows[0]["Approver"].ToString() != "")
                {
                    sql = "update Bus_StockInM set ApproverID='',Approver='',ApproverDate=NULL where docCode='" + doccode + "' ";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "辅料入库单反审核") > 0)
                    {
                        MessageBox.Show("反审核成功!", "提示", MessageBoxButtons.OK);
                        ListData();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("尚未审核了，不能反审核!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                MessageBox.Show("单据不存在，请检查!", "提示", MessageBoxButtons.OK);
                return;
            }
        }

        private void Approve(string doccode)
        {
            string sql;
            sql = @"SELECT  ApproverID, Approver, ApproverDate, IsSendToNC, SendToNCDate  FROM      Bus_StockInM where docCode='" + doccode + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                if (tb.Rows[0]["Approver"].ToString() == "")
                {
                    sql = "update Bus_StockInM set ApproverID='" + pub.sys_user.User_Id + "',Approver='" + pub.sys_user.UserName + "',ApproverDate=getdate() where docCode='" + doccode + "' ";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "辅料入库单审核") > 0)
                    {
                        MessageBox.Show("审核成功!", "提示", MessageBoxButtons.OK);
                        ListData();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("已经审核了，不能再次审核!", "提示", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                MessageBox.Show("单据不存在，请检查!", "提示", MessageBoxButtons.OK);
                return;
            }
        }
    }
}
